tags:
- Cpp
This Keyword in C++ (ENG)
this
PointerIf you're a C++ newbie, the this
keyword in a class can definitely be confusing, and you might find yourself asking, "What the heck is this
?"
According to cppreference, the this
expression is a pure rvalue expression, which represents the address value of the implicit object parameter. Simply put, you can consider this
as a pointer points to the current instance of the object.
When you use this
in a member function, it allows you to refer to the calling object itself. In this example down below, the this
pointer inside the showAddr
function points to the object obj
. The this
expression provides a way for member functions to refer to the instance of the class they were called on.
class MyClass {
public:
void showAddr() {
std::cout << "Address of this object: " << this << std::endl;
}
};
int main() {
MyClass obj;
obj.showAddr(); // Will print the address of the object `obj`
return 0;
}
this
You can see this
in every implicit object member function body, including member initializer list and lambda expression body (you can capture this
within a capture list).
class MyClass {
public:
// implicit member function getValue()
int getValue() const { // const member function
return value; // implicit form of return this->value;
}
private:
int value;
};
In any practice, explicitly using this
is often considered a good practice for clarity. Consider a scenario where you have passed a parameter with the exact same name as a class member variable. In the function setValue
, the use of this
helps to avoid ambiguity.
#include <iostream>
class MyClass {
public:
int getValue() const { // const member function
return this->value;
}
void setValue(int value) {
value = value; // parameter value will shadow the member with the same name
}
private:
int value = 50;
};
int main(){
MyClass obj;
obj.setValue(20);
std::cout << obj.getValue() << std::endl; // print 50
return 0;
}
const
Member FunctionIn the Const in C++ section, we talked about constant member functions in C++. const
member functions are not allowed to mutate the member variables of the class. So what is happening under the hood? Let's imagine we have a class as follows:
class MyClass {
public:
int getValue() const { // const member function
return this->value;
}
void setValue(int value) {
this->value = value;
}
private:
int value;
};
What really happens is a implicit casting, as we will examine this process:
int getValue() const {
return value;
}
// is the same as:
int getValue(const myClass* const this){
return this->value;
}
Because this casting is implicit, the const
is put on the outside of ()
to indicate that the member function cannot modify the object it is called on. Preserving the const-correctness of the function.
Because "this" was introduced into C++ before references were added.